package cn.edu.nuc.crm.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.edu.nuc.crm.entity.Cart;
import cn.edu.nuc.crm.entity.Product;
import cn.edu.nuc.crm.service.interfaces.CartService;
import cn.edu.nuc.crm.service.interfaces.ProductService;

@Controller
public class CartController {
	@Autowired
	private	 CartService cartService; 
	@Autowired
	private ProductService productService;
	
	
	/**
	 * 客户订票
	 * @param productid
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/buy",method=RequestMethod.GET)
	private String buy(int productid,Model model){
		Product product = productService.find(productid);
		int remain = product.getProductnum() - 1;
		product.setProductnum(remain);
		productService.updateByPrimaryKey(product);
		
		
		Cart cart = new Cart();
		cart.setProductid(productid);
		cart.setCartnum(1);
		cart.setProductname(product.getProductname());
		cart.setProductprice(product.getProductprice());
		cartService.insert(cart);
		
		return "redirect:cartlist1";
	}
	/**
	 * 放入订单
	 * @param cart
	 * @return
	 */
	@RequestMapping(value="insertCart",method=RequestMethod.POST)
	public String insert(Cart cart){	
		int count = cartService.insert(cart);		
		if( count > 0){	
			return "redirect:cartlist1";
		}
		return "cartlist1";	
	}

	@RequestMapping(value="cartlist1",method=RequestMethod.GET)
	public String list(Model model){
		List<Cart> list = cartService.cartlist();
		model.addAttribute("list", list);
		return "cartlist1";
   }
	/**
	 * 退票
	 * @param cartid
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/refund",method=RequestMethod.GET)
	public String refund(Integer cartid,Model model){
		
		Cart cart = cartService.detail(cartid);
		Product product = productService.find(cart.getProductid());
		int updateNum = product.getProductnum() + cart.getCartnum();
		product.setProductnum(updateNum);
		
		productService.updateByPrimaryKey(product);
		cartService.deleteByPrimaryKey(cartid);
		return "redirect:cartlist1";
	}
	/**
	 * 结算
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/clean",method=RequestMethod.POST)
	public String clean(Model model) throws Exception{
		cartService.cleanCart();	
		return "redirect:cartlist";
	}	
}
